import time

from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.db.models import Q
from django.shortcuts import render, redirect
from django.http.response import HttpResponse
from django.urls import reverse

from .models import Project
from django.core.paginator import Paginator
from django.core.paginator import PageNotAnInteger, EmptyPage


# Create your views here.
def index(request):
    cases = Project.objects.all().order_by("-id")
    p = request.GET.get('current_page', 1)
    p = int(p)
    paginator = Paginator(cases, 10)
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'projectManage/index.html', locals())


def transfer_the_page_range(p, paginator):
    """
    页数进行转换
    :param p:
    :param paginator:
    :return:
    """
    if paginator.num_pages > 5:
        if p - 5 < 1:
            page_range = range(1, 11)
        elif p + 5 > paginator.num_pages:
            page_range = range(p - 5, paginator.num_pages + 1)
        else:
            page_range = range(p - 5, p + 5)
    else:
        page_range = paginator.page_range
    return page_range


def create_project(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        project_name = request.POST.get('project_name')
        create_time = request.POST.get('create_time')
        project_describe = request.POST.get('project_describe')
        bu = request.POST.get('BU')
        remarks = request.POST.get('remarks')
        project = Project.objects.all()
        try:
            project.create(
                project_name=project_name, create_time=create_time, project_describe=project_describe,
                BU=bu, remarks=remarks)
            return redirect(referer)
        except IntegrityError:
            return HttpResponse("项目名称重复，请修改后再次提交！")


def search_project(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            project_name = request.GET.get('project_name', '')
            project_name = project_name.strip()
            project_bu = request.GET.get('project_bu', '')
            project_bu = project_bu.strip()
            if start_date and end_date:
                search_result = Project.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                       Q(create_time__lte=end_date + " 23:59:59"),
                                                       project_name__contains=project_name,
                                                       BU__contains=project_bu).order_by('-id')
            elif start_date:
                search_result = Project.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                       project_name__contains=project_name,
                                                       BU__contains=project_bu).order_by('-id')
            elif end_date:
                search_result = Project.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                       project_name__contains=project_name,
                                                       BU__contains=project_bu).order_by('-id')
            else:
                search_result = Project.objects.filter(project_name__contains=project_name,
                                                       BU__contains=project_bu).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'projectManage/search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def search_result_export(request):
    return HttpResponse("Not Yet!!!")


def edit_project(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        project_id = request.POST.get('project_id')
        project_id = int(project_id)
        project_name = request.POST.get('project_name')
        project_describe = request.POST.get('project_describe')
        BU = request.POST.get('BU')
        update_time = time.strftime("%Y-%m-%d %H:%M:%S")
        remarks = request.POST.get('remarks')
        project = Project.objects.filter(id=project_id)
        try:
            project.update(project_name=project_name, update_time=update_time, project_describe=project_describe,
                           remarks=remarks, BU=BU)
            return redirect(referer)
        except IntegrityError as error1:
            return HttpResponse("项目名称重复，请修改后再次提交！")


def project_delete(request, project_id):
    Project.objects.get(pk=project_id).delete()
    referer = request.headers.get('Referer')
    return redirect(referer)
